package com.wispx.gateway.core.netty;

import com.wispx.gateway.config.config.Config;
import com.wispx.gateway.config.config.NettyConfig;
import com.wispx.gateway.core.container.Lifecycle;
import com.wispx.gateway.core.netty.handler.NettyHttpServerHandler;
import com.wispx.gateway.core.netty.processor.NettyProcessor;
import com.wispx.gateway.core.util.OSUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * NettyHttpServer 服务端，用于接受请求
 */
@Slf4j
public class NettyHttpServer implements Lifecycle {


    private Config config;
    private ServerBootstrap serverBootstrap;
    private EventLoopGroup eventLoopGroupBoss;
    private EventLoopGroup eventLoopGroupWorker;
    private NettyProcessor nettyProcessor;
    private AtomicBoolean start = new AtomicBoolean(false);


    public NettyHttpServer(Config config, NettyProcessor nettyProcessor) {
        this.config = config;
        this.nettyProcessor = nettyProcessor;
    }

    // 启动 Netty 服务器
    @Override
    @SneakyThrows(InterruptedException.class)
    public void start() {
        if (config == null || nettyProcessor == null || !start.compareAndSet(false, true)) {
            return;
        }
        NettyConfig netty = config.getNetty();
        eventLoopGroupBoss = OSUtil.supportEpoll() /* OS是否支持epoll */ ?
                new EpollEventLoopGroup(netty.getEventLoopBossGroupNum(), new DefaultThreadFactory("epoll-http-server-boss-nio")) :
                new NioEventLoopGroup(netty.getEventLoopBossGroupNum(), new DefaultThreadFactory("default-http-server-boss-nio"));
        eventLoopGroupWorker = OSUtil.supportEpoll() ?
                new EpollEventLoopGroup(netty.getEventLoopWorkerGroupNum(), new DefaultThreadFactory("epoll-http-server-worker-nio")) :
                new NioEventLoopGroup(netty.getEventLoopWorkerGroupNum(), new DefaultThreadFactory("epoll-http-server-worker-nio"));
        serverBootstrap = new ServerBootstrap()
                .group(eventLoopGroupBoss, eventLoopGroupWorker)
                .channel(OSUtil.supportEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)            // TCP连接的最大队列长度
                .option(ChannelOption.SO_REUSEADDR, true)          // 允许端口重用
                .option(ChannelOption.SO_KEEPALIVE, true)          // 保持连接检测
                .childOption(ChannelOption.TCP_NODELAY, true)      // 禁用Nagle算法，适用于小数据即时传输
                .childOption(ChannelOption.SO_SNDBUF, 65535)       // 设置发送缓冲区大小
                .childOption(ChannelOption.SO_RCVBUF, 65535)       // 设置接收缓冲区大小
                .localAddress(new InetSocketAddress(config.getPort())) // 绑定端口
                .childHandler(new ChannelInitializer<SocketChannel>() { // 连接上的channel
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new HttpServerCodec()) // HTTP 解码器
                                .addLast(new HttpObjectAggregator(config.getNetty().getMaxLength())) // 聚合HTTP请求，聚合为 FullHttpRequest
                                .addLast(new HttpServerExpectContinueHandler()) // 处理 HTTP 100 Continue 请求
                                .addLast(new NettyHttpServerHandler(nettyProcessor));// 自定义处理器
                    }
                });
        serverBootstrap.bind().sync();
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); // netty 检测资源泄露机制
        log.info("gateway startup on port:{}", config.getPort());
    }

    @Override
    public void shutdown() {
        if (!start.get()) {
            return;
        }
        eventLoopGroupBoss.shutdownGracefully();
        eventLoopGroupWorker.shutdownGracefully();
        serverBootstrap.clone();
    }

    @Override
    public boolean isStart() {
        return start.get();
    }
}
